package com.goldsprite.gameframeworks.timeline;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;

public abstract class TimeLineTask {
	public boolean isCompleted = true;
	private float delta;
	private boolean waitStarted;
	private float waitTicker, waitDuration;
	protected int executeIndex;

	/**
	 * 创建序列事件
	 */
	@SafeVarargs
	public static TimeLineTask sequence(Consumer<TimeLineTask>... events) {
		return new SequenceTask(new ArrayList<>(Arrays.asList(events)));
	}

	/**
	 * 创建条件等待事件
	 */
	public static TimeLineTask threadWait(Condition condition) {
		return new ThreadWaitTask(condition);
	}

	/**
	 * 在新线程中执行时间线事件
	 */
	public static void newThread(TimeLineTask event) {
		new Thread(event::execute).start();
	}

	public void wait(float seconds) {
		isCompleted = false;
		if(!waitStarted) {
			waitStarted = true;
			waitTicker = seconds;
		}
		else if(waitTicker > 0){
			waitTicker -= delta;
		}else{
			isCompleted = true;
			waitStarted = false;
		}
	}

	public TimeLineTask setDelta(float delta) {
		this.delta = delta;
		return this;
	}

	public abstract TimeLineTask execute();

	public void again() {
		again(0);
	}
	public void again(int index) {
		executeIndex = index;
		isCompleted = false;
	}

	// ===== 条件接口 =====
	public interface Condition {
		boolean isSatisfied();
	}

	// ===== 序列事件实现 =====
	private static class SequenceTask extends TimeLineTask {
		private final List<Consumer<TimeLineTask>> events;

		public SequenceTask(List<Consumer<TimeLineTask>> events) {
			this.events = events;
		}

		@Override
		public SequenceTask execute() {
			for(; executeIndex < events.size(); executeIndex++) {
				Consumer<TimeLineTask> event = events.get(this.executeIndex);

				isCompleted = true;  // 重置完成状态
				event.accept(this);  // 执行当前事件
				if (!isCompleted) return this;  // 未完成就退出遍历，返回未完成
			}

			return this;
		}
	}

	// ===== 等待事件实现 =====
	private static class ThreadWaitTask extends TimeLineTask {
		private final Condition condition;

		public ThreadWaitTask(Condition condition) {
			this.condition = condition;
		}

		@Override
		public ThreadWaitTask execute() {
			// 轮询等待直到条件满足
			while (!condition.isSatisfied()) {
				try {
					Thread.sleep(16); // 约60FPS的等待间隔
				} catch (InterruptedException e) {
					Thread.currentThread().interrupt();
					break;
				}
			}
			return this;
		}
	}


}
